import './data.css'
import React, { useState } from "react";

import {Table, Button, Modal, Space, Form, Input, InputNumber, message } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import PubSub from "pubsub-js";
import axios from "axios";

const { confirm } = Modal;


// 请求表格数据
const QueryTableData  = () => {
  let data = { message:'queryimg_ten' }
  let url = '/registrationapi/queryimg'
  axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
    ).then(res=>{
      if(res.status === 200 && res.data.code === 0){
        originData.splice(0,originData.length);
        for(let i = 0; i < res.data.img_list.length; i++){
          originData.push(res.data.img_list[i])
          originData[i].key = i.toString()
        }
        console.log(originData)
      } else{
        console.log(res.data.msg)
        message.error(res.data.msg)
      }
  })
}

// 初始化表格数据
const originData = [];
QueryTableData();

// 单元编辑函数
const EditableCell = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `请输入 ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

const EditableTable = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState(originData);
  const [editingKey, setEditingKey] = useState('');

  const isEditing = (record) => record.key === editingKey;

  // 点击编辑按钮事件
  const edit = (record) => {
    form.setFieldsValue({
      p_name: '',
      p_sex: '',
      p_age: '',
      doctor: '',
      stage: '',
      date: '',
      image_name: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  // 点击删除按钮事件
  const delete_row = (record) => {
    confirm({
      title: `是否要删除所选项？`,
      icon: <ExclamationCircleOutlined />,
      content: '删除后将无法恢复',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        let upload_data = { image_id: record.id }
        let url = '/registrationapi/deleteimg'
        axios.post(url, upload_data, {headers: {'Content-Type': 'application/json'}}
          ).then(res=>{
            if(res.status === 200 && res.data.code === 0){
              const newData = [];
              originData.splice(0,originData.length);
              for(let i = 0; i < res.data.img_list.length; i++){
                newData.push(res.data.img_list[i])
                newData[i].key = i.toString()
                originData[i] = newData[i]
              }
              setData(newData)
              message.success('删除成功！')
            } else{
              console.log(res.data.msg)
              message.error(res.data.msg)
            }
        })
      },
      onCancel() {
        console.log('取消');
      },
    });
  };

  // 点击取消按钮事件
  const cancel = () => {
    setEditingKey('');
  }

  // 点击保存按钮事件
  const save = async(key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if(index > -1){
        const item = newData[index];
        newData.splice(index, 1, {...item, ...row});
        let data = {
          image_id: newData[index].id,
          p_name: newData[index].p_name,
          p_sex: newData[index].p_sex,
          p_age: newData[index].p_age,
          doctor: newData[index].doctor,
          stage: newData[index].stage,
          date: newData[index].date,
          image_name: newData[index].image_name,
        }
        let url = '/registrationapi/editimg'
        axios.post(url, data, {headers: {'Content-Type': 'application/json'}}
          ).then(res=>{
            if(res.status === 200 && res.data.code === 0){
              originData.splice(0,originData.length);
              for(let i = 0; i < res.data.img_list.length; i++){
                originData[i] = newData[i]
              }
              setData(newData)
              setEditingKey('')
              message.success('编辑成功！')
            } else{
              console.log(res.data.msg)
              message.error(res.data.msg)
              setEditingKey('')
            }
        })
      } else {
        console.log('-1')
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo){
      console.log('Validate Failed:', errInfo);
    }
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'p_name',
      editable: true,
    },
    {
      title: '性别',
      dataIndex: 'p_sex',
      editable: true,
    },
    {
      title: '年龄',
      dataIndex: 'p_age',
      editable: true,
    },
    {
      title: '主治医生',
      dataIndex: 'doctor',
      editable: true,
    },
    {
      title: '诊疗阶段',
      dataIndex: 'stage',
      editable: true,
    },
    {
      title: '拍摄时间',
      dataIndex: 'date',
      editable: true,
    },
    {
      title: '图片名称',
      dataIndex: 'image_name',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (text, record) => {
        const editable = isEditing(record);
        return editable ? (
          <Space>
            <Button type="primary" onClick={() => save(record.key)}>保存</Button>
            <Button type="danger" onClick={cancel}>取消</Button>
          </Space>
        ) : (
          <Space>
            <Button type="primary" disabled={editingKey !== ''} onClick={() => edit(record)}>编辑</Button>
            <Button type="danger" onClick={() => delete_row(record)}>删除</Button>
          </Space>
        )
      }
    }
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: col.dataIndex === 'p_age' ? 'number' : 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      })
    }
  });

  return (
    <div className="data-list">
      <Form form={form} component={false}>
        <Table
          components={{
            body:{
              cell: EditableCell,
            }
          }}
          columns={mergedColumns}
          dataSource={data}
          pagination={{
            onChange: cancel,
          }}
        />
      </Form>
    </div>
  )
};


export default class Data extends React.Component{
  componentDidMount() {
    PubSub.subscribe('sendUploadParam', (name, uploadState) => {
      QueryTableData()
    })
    QueryTableData()
    let orderNumber = 4;
    PubSub.publish("sendOrderNumber4", orderNumber);
  }

  render() {
    return <EditableTable/>;
  }
}